package ChooseLbAction;

use strict;

use Athena::WebAPI::Response;
use Athena::ChooseLbView;
use Athena::ErrorView;

sub execute {
  my $stInvocant = shift(@_);
  my $rRequest = shift(@_);
  my $cConn = shift(@_);
  my %hParams = ( @_ );
  my $stParams = \%hParams;
  my $rResponse = undef;
  my $stErrMsg = "";
  my $stActionName = 'ChooseLbAction';
  $rRequest->action($stActionName);
  my $stAction = $rRequest->param($stActionName);
  my $rView;
  my $stLb = $rRequest->cookie('AthenaEngineUrl') 
    || $rRequest->cookie('AthenaEngineHost') 
      . ":" . $rRequest->cookie('AthenaEnginePort');

  my $rHiddenFields = {
		       $rRequest->getActionParam() => $rRequest->action(),
		       $stActionName => '',
		      };

  
  if ($cConn->getUrl()) {
    $rView = ErrorView->new('err_msg'=>'Bad Action choice',
			    'err_body'=>'This action is not possible using http access method.<br>You must goto Method tab to change method to "athena".',
			    'body_style'=>$stParams->{body_style}, 
			    'table_style'=>$stParams->{table_style},
			   );
  }
  elsif (($cConn) 
      && (getEngineList($rRequest, $cConn, $stParams))) {
    $rView = ChooseLbView->new('lb' => $stLb,
			       'err_msg' => $stErrMsg,
			       'hidden_fields' => $rHiddenFields,
			       'action_name' => $stActionName,
			       'body_style' => $stParams->{body_style},
			       'table_style' => $stParams->{table_style},
			       'engines' => $stParams->{engines},
			      );
  }
  else {
    $rView = ErrorView->new('err_msg'=>'Error interacting with athena daemon',
			    'err_body'=>"$!",
			    'body_style'=>$stParams->{body_style}, 
			    'table_style'=>$stParams->{table_style},
			   );
  }
  $rResponse = Response->new($rView);
  
  return $rResponse;
}

sub getEngineList {
  my $rRequest = shift(@_);
  my $cConn = shift(@_);
  my $stParams = shift(@_);
  my $stRecv;
  my %hEngines = ();
  my $stEngines = \%hEngines;
  my $rv;

  if ($cConn) {
    if ($rv = $cConn->send("engine"))	{
      $stRecv = $cConn->recv();
    }
  }

  my @lines = split("\n", $stRecv);
  my $line;
  my $engine;
  while (@lines) {
    $line = shift(@lines);
    chomp($line);
    if ($line =~ /Engine name: /) {
      $engine = substr($line, index($line, ": ") + 2);
      $stEngines->{$engine}->{exists} = 1;
    }
    elsif (length($line) > 0) {
      # remove preceding spaces
      $line = substr($line, 2);
      my $parm = substr($line, 0, index($line, ":"));
      my $arg = substr($line, index($line, " "));
      $stEngines->{$engine}->{$parm} = $arg;
    }
  }
  $stParams->{engines} = $stEngines;
  return $rv;
}

1;
